using MediatR;
using Microsoft.AspNetCore.Mvc;
using RBAC.ErrorCode;
using RBAC.Write.Api.Application.Command.ArrivalInspection;
using System.IO;
using System.Threading.Tasks;

namespace RBAC.Write.Api.Controllers.ArrivalInspection
{
    /// <summary>
    /// 到货检验 控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ArrivalInspectionController : ControllerBase
    {
        private readonly IMediator _mediator;

        public ArrivalInspectionController(IMediator mediator)
        {
            _mediator = mediator;
        }

        /// <summary>
        /// 新增到货检验（主表+明细+附件）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<long>> Create([FromBody] CreateArrivalInspectionCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 上传到货检验附件（文件直传）
        /// </summary>
        [HttpPost]
        [Consumes("multipart/form-data")]
        public async Task<APIResult<string>> UploadAttachment([FromForm] UploadArrivalInspectionAttachmentForm form)
        {
            if (form == null || form.File == null || form.File.Length == 0)
            {
                return new APIResult<string> { Code = APIEnums.Fail, Msg = "文件为空", Data = string.Empty };
            }

            await using var ms = new MemoryStream();
            await form.File.CopyToAsync(ms);
            var cmd = new UploadArrivalInspectionAttachmentCommand
            {
                FileName = form.File.FileName,
                FileBytes = ms.ToArray(),
                ContentType = form.File.ContentType
            };
            return await _mediator.Send(cmd);
        }

        /// <summary>
        /// 编辑到货检验（覆盖明细与附件）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<long>> Edit([FromBody] UpdateArrivalInspectionCommand command)
        {
            return await _mediator.Send(command);
        }

        /// <summary>
        /// 删除到货检验（软删除主表，物理删除子表）
        /// </summary>
        [HttpPost]
        public async Task<APIResult<long>> Delete([FromBody] DeleteArrivalInspectionCommand command)
        {
            return await _mediator.Send(command);
        }
    }
}
